package com.xuanjia.smart_interview.satoken;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.xuanjia.smart_interview.common.ErrorCode;
import com.xuanjia.smart_interview.exception.ThrowUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 设备工具类
 */
public class DeviceUtils {
    public static String getReuqestDeivce(HttpServletRequest request){
        String userAgentString = request.getHeader(Header.USER_AGENT.toString());
        UserAgent userAgent = UserAgentUtil.parse(userAgentString);
        ThrowUtils.throwIf(userAgent == null, ErrorCode.OPERATION_ERROR,"多端设备登陆啦！");
        String device = "pc";
        if (isMiniprogram(userAgentString)){
            device = "miniprogram";
        } else if (isPad(userAgentString)) {
            device = "pad";
        } else if (userAgent.isMobile()) {
            device = "mobile";
        }
        return device;
    }

    //判断小程序登录
    public static Boolean isMiniprogram(String userAgentString){
        return StrUtil.containsIgnoreCase(userAgentString,"MicorMessanger")
                && StrUtil.containsIgnoreCase(userAgentString,"Miniprogram");
    }
    public static Boolean isPad(String userAgentString){
        boolean ipad = StrUtil.containsIgnoreCase(userAgentString, "ipad");
        boolean androidIpad = StrUtil.containsIgnoreCase(userAgentString,"Android")
                && !StrUtil.containsIgnoreCase(userAgentString,"Mobile");
        return ipad || androidIpad;
    }
}
